package errors

import (
	"bytes"
	"strings"
	"text/template"

	"gitee.com/zawei/yggdrasil/pkg/utils/xstrings"
)

var errorsTemplate = `const (
{{ range .Errors }}
	{{print "Err" (StrToCamelCase (StrToUpperFirst .Value))}} = "{{StrToCamelCase (print .Name  (StrToUpperFirst .Value))}}" {{TrimSpace .Comment}}
{{- end }}
)

{{ range .Errors }}

func Is{{.Value}}(err error) bool {
	return errors.Reason(err) == {{print "Err" (StrToCamelCase (StrToUpperFirst .Value))}}
}
{{- end }}
`

type errorInfo struct {
	Name    string
	Value   string
	Comment string
}

type errorWrapper struct {
	Errors []*errorInfo
}

func (e *errorWrapper) execute() string {
	buf := new(bytes.Buffer)
	tmpl, err := template.New("errors").Funcs(map[string]interface{}{
		"StrToCamelCase":  xstrings.StrToCamelCase,
		"StrToUpperFirst": xstrings.StrToUpperFirst,
		"TrimSpace":       strings.TrimSpace,
	}).Parse(errorsTemplate)
	if err != nil {
		panic(err)
	}
	if err := tmpl.Execute(buf, e); err != nil {
		panic(err)
	}
	return string(buf.Bytes())
}
